/* eslint-disable */
import axios from 'axios'
import router from '@/router'
import Toast from 'common/Toast/index'
import store from '@/store/index'

/**
* 定义请求常量
* TIME_OUT、ERR_OK
*/
export const TIME_OUT =38000;    // 请求超时时间
export const ERR_OK = true;      // 请求成功返回状态，字段和后台统一
export const API_HOST = process.env.API_HOST   // 引入全局url，定义在全局变量process.env中

// 请求超时时间
axios.defaults.timeout = TIME_OUT

// 封装请求拦截
axios.interceptors.request.use(config => {
		// 发起请求，取消掉当当前正在进行的相同请求
		return config
	},
	error => {
		return Promise.reject(error)
	}
)
// 封装响应拦截，判断token是否过期
axios.interceptors.response.use(
  response => {
  	return response
  },
  error  => {
  	if (error.response) {
  		switch (error.response.status) {
  			case 400:
  				error.message = 'Status:400'
  				break;
  			case 401:
  				error.message = 'Status:401'
  				break;
  			case 403:
  				error.message = 'Status:403'
  				break;
  			case 404:
  				error.message = 'Status:404'
					router.toReplace('/error/404', {err: '内容不存在或者已被删除'})
  				break;
  			case 405:
  				error.message = 'Status:405'
  				break;
  			case 408:
  				error.message = 'Status:408'
  				break;
  			case 500:
  				error.message = 'Error:500'
					router.toReplace('/error/404', {err: '服务器出错咯!'})
  				break;
  			case 501:
  				error.message = 'Status:501'
  				break;
  			case 502:
  				error.message = 'Status:502'
  				break;
  			case 503:
  				error.message = 'Status:503'
  				break;
  			case 504:
  				error.message = 'Network Timeout 504'
  				break;
  			default:
  				error.message = `ERROR:${error.response.status}`
					break;
  		}
  	}
		else if(error.request){
			// 捕获超时请求
			error.message = 'TimeOut';
		}
		return Promise.reject(error);
  }
)
// 封装post请求
export function Axios(requestUrl, params, type = 'post') {
	// let userInfo = store.state.userInfo;
	// params.token = userInfo.token;
	// params.u_id = userInfo.u_id;
  return new Promise((resolve,reject) => {
    axios({
      url: requestUrl,
      method: type,
      data: params
    }).then(res => {
      if (res.data.code === 401) {
				// 用户状态非法
				console.log(res.data);
				Toast.hideLoading();
				router.toReplace('/login')
      } else {
        resolve(res.data)
      }
    }).catch(err => {
			Toast.hideLoading();
      // router.togo('/error/404', {err: err.toString()})
      reject(err);
    })
  })
}
